package com.ler.yrmall.ware.listener;

import com.alibaba.fastjson.JSON;
import com.ler.yrmall.order.api.OrderApi;
import com.ler.yrmall.order.dto.OrderDTO;
import com.ler.yrmall.ware.entity.WareOrderTaskDetailEntity;
import com.ler.yrmall.ware.entity.WareOrderTaskEntity;
import com.ler.yrmall.ware.service.WareOrderTaskDetailService;
import com.ler.yrmall.ware.service.WareOrderTaskService;
import com.ler.yrmall.ware.service.WareSkuService;
import com.ler.yrmall.ware.constant.WareConstant;
import com.ler.yrmall.ware.dto.StockDetailDTO;
import com.ler.yrmall.ware.dto.StockLockedDTO;
import com.ler.yrmall.basic.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Leron
 * @version 1.0
 */
@Slf4j
@Service
@RocketMQMessageListener(consumerGroup = "ware-consumer-group",topic = WareConstant.STOCK_LOCK_TOPIC)
public class WareAutoReleaseListener implements RocketMQListener<StockLockedDTO> {

    @DubboReference
    private OrderApi orderApi;

    @Resource
    private WareSkuService wareSkuService;

    @Resource
    private WareOrderTaskService orderTaskService;

    @Resource
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Override
    public void onMessage(StockLockedDTO stockLockedDto) {
        log.info("解锁库存:{}", JSON.toJSONString(stockLockedDto));

        if (stockLockedDto == null || stockLockedDto.getDetail() == null || stockLockedDto.getTaskId() == null) return;

        // 获得锁库存的详情信息
        StockDetailDTO detail = stockLockedDto.getDetail();
        /**
         * 解锁
         * 查询数据库种这个订单的加锁信息
         * 解锁
         *  订单情况
         *      没有此订单 解锁
         *      订单被取消 解锁
         */
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = wareOrderTaskDetailService.getById(detail.getId());
        if (wareOrderTaskDetailEntity != null) {
            Long id = stockLockedDto.getTaskId();
            WareOrderTaskEntity wareOrderTaskEntity = orderTaskService.getById(id);
            String orderSn = wareOrderTaskEntity.getOrderSn();
            Result<OrderDTO> r = orderApi.getOrderByOrderSn(orderSn);
            OrderDTO data = r.getData();
            if (data == null || data.getStatus() == 4) {
                //解锁
                wareSkuService.unStockLock(wareOrderTaskDetailEntity.getSkuId(),wareOrderTaskDetailEntity.getWareId(),
                        wareOrderTaskDetailEntity.getId(),wareOrderTaskDetailEntity.getSkuNum());
            }
        }
    }


}
